package bbs.db; 

import java.io.*; 
import java.util.Collection;

import org.apache.ibatis.session.*; 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ConnectionFactory {
	
	/**
	 * Log4j logger
	 */
	static final Logger logger = LogManager.getLogger(ConnectionFactory.class);
	
	private static final ConnectionFactory connectionFactory = new ConnectionFactory();

	private SqlSessionFactory sessionFactory = null ;  
	
	private ConnectionFactory() { 
		try{
			String fileName = "MyBatisConfig.xml"; 
			InputStream in = ConnectionFactory.class.getResourceAsStream( fileName );
			Reader reader = new InputStreamReader( in, "UTF-8" ); 
			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public SqlSessionFactory getSessionFactory(){
		return sessionFactory;
	} 
	
	public SqlSession getSqlSession() {
		return sessionFactory.openSession();
	}
	
	public void printStatmentNames() {
		Collection<String> col = sessionFactory.getConfiguration().getMappedStatementNames();
		
		if( col.size() < 1 ) {
			logger.trace( "There is no mapped stmt names." );
		} else { 
			for( String name : col ) {
				logger.trace( "name: " + name );
			}
		}
	}
	
	public static ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}
	
}